package com.jews.example.demo.domain.user.service;

import com.jews.common.constants.CodeEnum;
import com.jews.common.exception.BusinessException;
import com.jews.example.demo.domain.user.User;
import com.jews.example.demo.domain.user.creator.UserCreator;
import com.jews.example.demo.domain.user.mapper.UserMapper;
import com.jews.example.demo.domain.user.repository.UserRepository;
import com.jews.example.demo.domain.user.updater.UserUpdater;
import com.jews.example.demo.domain.user.vo.UserVO;
import com.jews.jpa.support.EntityOperations;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

//@Transactional
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements IUserService {

    private final UserRepository UserRepository;

    /**
     * createImpl
     */
    @Override
    public Long createUser(UserCreator creator) {
        Optional<User> user = EntityOperations.doCreate(UserRepository)
                .create(() -> UserMapper.INSTANCE.dtoToEntity(creator))
                .update(User::init)
                .execute();
        return user.isPresent() ? user.get().getId() : 0;
    }

    /**
     * update
     */
    @Override
    public void updateUser(UserUpdater updater) {
        EntityOperations.doUpdate(UserRepository)
                .loadById(updater.getId())
                .update(updater::updateUser)
                .execute();
    }

    /**
     * valid
     */
    @Override
    public void validUser(Long id) {
        EntityOperations.doUpdate(UserRepository)
                .loadById(id)
                .update(User::valid)
                .execute();
    }

    /**
     * invalid
     */
    @Override
    public void invalidUser(Long id) {
        EntityOperations.doUpdate(UserRepository)
                .loadById(id)
                .update(User::invalid)
                .execute();
    }

    /**
     * findById
     */
    @Override
    public UserVO findById(Long id) {
        Optional<User> user = UserRepository.findById(id);
        return new UserVO(user.orElseThrow(() -> new BusinessException(CodeEnum.NotFindError)));
    }
}
